package com.example.myapplication.ui;

import android.app.Application;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;

import com.example.myapplication.database.InitDataBase;
import com.example.myapplication.dao.NoteDao;
import com.example.myapplication.entity.Note;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class NoteViewModel extends AndroidViewModel {

    private final NoteDao noteDao;
    private final LiveData<List<Note>> allNotes;
    private final ExecutorService executorService; // 用来在子线程执行数据库操作

    public NoteViewModel(@NonNull Application application) {
        super(application);
        InitDataBase db = InitDataBase.getDatabase(application); // 改成 getDatabase（我们下面会写）
        noteDao = db.noteDao();
        allNotes = noteDao.getAllNotes(); //  确保 NoteDao 返回 LiveData<List<Note>>
        executorService = Executors.newSingleThreadExecutor();
    }

    //        获取所有笔记
    public LiveData<List<Note>> getAllNotes() {
        return allNotes;
    }

    //                       插入
    public void insert(Note note) {
        executorService.execute(() -> noteDao.insert(note));
    }

    // 删除
    public void delete(Note note) {
        executorService.execute(() -> noteDao.delete(note));
    }
}
